package com.book.chapter.service;

import com.book.book.NovelSiteEnum;
import com.book.chapter.entity.Chapter;
import com.book.book.service.AbstractSpider;
import com.book.common.utils.NovelSpiderUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

/***
 * @Author Lin
 * @Date Create By 12:28 2017/10/4
 * @Description 抓取任意小说网站小说的章节列表
 */
public abstract class AbstractChapterSpider extends AbstractSpider implements ChapterSpider {

    @Override
    public List<Chapter> getChapter(String url) {
        try {
            String result = super.crawl(url);
            Document doc = Jsoup.parse(result);
            doc.setBaseUri(url);
            Elements elements = doc.select(NovelSpiderUtil.getContext(NovelSiteEnum.getEnumByUrl(url)).get("chapter-list-selector"));
            List<Chapter> chapters = new ArrayList<>();
            for (Element element : elements) {
                Chapter chapter = new Chapter();
                chapter.setChapterTitle(element.text());
                chapter.setChapterUrl(element.absUrl("href"));
                chapters.add(chapter);
            }
            return chapters;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
